<?php
/**
 * 交费文件
 *
 * @author lwb
 */
namespace app\wechat\controller;

class Repayment extends Common {

    public function __construct() {
        parent::__construct();
    }
    
    /**
     * 交费列表
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-07T14:15:05+0800
     * @param    [type]
     * @return   [type]
     */
    public function repaymentList($params)
    {
        // 账单ID
        $b_id = !empty($params['b_id']) ? $params['b_id'] : session('b_id');
        $order = $this->getWS('credit', 'apply@applyInfo', ['b_id'=>$b_id]);
        if($order['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '获取交费列表失败']);
        }
        //已放款就读交费列表
        if($order['result']['b_status'] >= '3000'){
            $result = $this->getWS('credit', 'repayment@repaymentList', ['b_id' => $b_id]);
            if ($result['status'] != '2000') {
                return $this->parse_data(['code' => 5000, 'msg' => '获取交费列表失败']);
            }

            $data = [];
            if ($result['result']) {
                foreach ($result['result'] as $k=>$val) {
                    $total_price += $val['r_capital'];
                    $service_fee += $val['r_service_fee'];
                    $interest+=$val['r_interest'];
                    $data['list'][$k]['amount_due'] = floatval($val['r_capital']) + floatval($val['r_service_fee']) + floatval($val['r_interest']) + floatval($val['r_expired_amount']) + floatval($val['r_call_fee']) + floatval($val['r_w_fee']) - floatval($val['r_derate_amount']);
                    $data['list'][$k]['status_name'] = config('dict.repayment_status')[$val['r_status']];
                    $data['list'][$k]['period_no'] = $val['period_no'];
                    $data['list'][$k]['repay_date'] = date_format(date_create($val['r_return_day']),'Y-m-d');
                }
                $data['total_price'] = $total_price;
                $data['service_fee'] = sprintf("%1\$.2f",$service_fee+$order['result']['down_amount']+$interest);
                $data['total_repay_price']=sprintf("%1\$.2f",$data['total_price']+$data['service_fee']);
                $data['down_amount'] = sprintf("%1\$.2f",$order['result']['down_amount']);
                $data['b_period'] = count($result['result']);
            }
        }else{
            //没有就读交费计划   
            $condition['orderPrice'] = $order['result']['b_borrow_amount'];
            $condition['periods'] = $order['result']['b_period'];
            $condition['orderRate'] = $order['result']['p_rate'];
            $condition['rateType'] = $order['result']['p_period_type'];
            $condition['repaymentType'] = $order['result']['p_return_type'];
            $condition['payTime'] = $order['result']['start_rent_date'];
            $condition['nextDays'] = $order['result']['p_advance_return_day'];
            $condition['partnerRepayTime'] = $order['result']['partner_repay_time'];
            $condition['partnerRepayDay'] = $order['result']['partner_repay_day'];
            $condition['nextMonths'] = $order['result']['partner_repay_month'];
            $condition['serviceFee'] = $order['result']['p_service_price'];
            $condition['partnerFee'] = $order['result']['p_partner_service'];
            $condition['p_one_time_amount'] = $order['result']['p_one_time_amount'];
            $condition['p_x_month'] = $order['result']['p_x_month'];
            $condition['p_x_proportion'] = $order['result']['p_x_proportion'];
            $condition['p_y_month'] = $order['result']['p_y_month'];
            $condition['p_y_proportion'] = $order['result']['p_y_proportion'];
            $condition['downAmount'] = $order['result']['down_amount'];
            $result = $this->getWS('channel', 'repayment@repaymentList', $condition);
            if($result['status'] != '2000'){
                return $this->parse_data(['code' => 5000, 'msg' => '获取交费列表失败']);
            }

            $data = [];
            if($result['result']){
                foreach($result['result'] as $k=>$val){
                    $order_price += floatval($val['capital']);
                    $service_fee += $val['service_fee'];
                    $interest+=$val['interest'];
                    $data['list'][$k]['amount_due'] = sprintf("%1\$.2f",($val['capital'])+floatval($val['service_fee'])+floatval($val['interest']));
                    $data['list'][$k]['period_no'] = $val['sort_order'];
                    $data['list'][$k]['repay_date'] = date_format(date_create($val['repay_date']),'Y-m-d');
                    $data['list'][$k]['status_name'] = '未交费';
                }
                $data['total_price'] = sprintf("%1\$.2f",$order['result']['b_borrow_amount']+$order['result']['down_amount']);
                $data['service_fee'] = sprintf("%1\$.2f",$service_fee+$interest);
                $data['total_repay_price'] = sprintf("%1\$.2f",$data['total_price']+$data['service_fee']);
                $data['down_amount'] = sprintf("%1\$.2f",$order['result']['down_amount']);
                $data['b_period'] = count($result['result']);
            }
        }

        return $this->parse_data(['data'=>$data]);
    }
    /**
     * 我要缴费
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-14T16:47:50+0800
     * @param    [type]
     * @return   [type]
     */
    public function myRepaymentList($params){ 
        $result = $this->getWS('credit', 'repayment@myRepaymentList', ['u_code' => $this->uid]);     
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取交费信息失败']);
        }

        $datas = $data = $status = [];
        if($result['result']){
            $isSetShow = $showId = 0;
            foreach ($result['result'] as $k=>&$v) {
                if(!$isSetShow){
                    if(in_array($v['r_status'],['0','2'])){
                        $showId = $k;
                        $isSetShow = 1;
                    }
                }
                $v['month'] = date('m', strtotime($v['r_return_day']));
                $v['order_no'] = $v['b_id']?orderNo($v['b_id'],$v['b_apply_time']):'';
                $v['r_status_name'] = config('dict.repayment_status')[$v['r_status']]?:'';
                $v['partner_type_name'] = config('dict.partner_type')[$v['partner_type']]?:'';
                $repayment_amt = floatval($v['r_capital']) + floatval($v['r_service_fee']) + floatval($v['r_interest']) + floatval($v['r_expired_amount']) + floatval($v['r_call_fee']) + floatval($v['r_w_fee']) - floatval($v['r_derate_amount']);
                $v['repayment_amt'] = sprintf("%1\$.2f", $repayment_amt)?:'';
                $v['ok_repayment_amt'] = ($v['r_status'] == '0' || $v['r_status'] == '2') ?'0.00':sprintf("%1\$.2f", $repayment_amt);
                
                //按月分组
                $data[date('Y-m', strtotime($v['r_return_day']))][] = $repayment_amt?:'0.00';
                // if(intval(date('Ym', strtotime($v['r_return_day']))) <= intval(date('Ym', time()))){
                    if($v['r_status'] == '1' || $v['r_status'] == '3'){
                        $status[] = '已交费';
                    }else{
                        $status[] = '立即缴费';
                    }
                // }else{
                //     $status[] = '未出账';
                // }
            }
            $i = 0;
            foreach ($data as $k => $val) {
                $datas[$i]['sum_amt'] = sprintf("%1\$.2f", array_sum($val))?:'0.00';
                $datas[$i]['count'] = count($val)?:'0';
                $datas[$i]['month'] = date('m',strtotime($k))?:'';
                $datas[$i]['status_name'] = $status[$i];
                $i++;
            }
        }
        
        return $this->parse_data(['data' => ['countList' => $datas, 'infoList' => $result['result'], 'showId' => $showId]]);
        
    }

    /**
     * 立即缴费
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-15T17:24:52+0800
     * @param    [type]
     * @return   [type]
     */
    public function payment($params) {
        if (empty($params['b_id']) || empty($params['period_no'])) {
            return $this->parse_data(['code' => 5000, 'msg' => '交费失败']);
        }
        //检查
        $repayment = $this->getWS('credit', 'repayment@checkRepayment', ['b_id' => $params['b_id']]);
        if($repayment['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => $repayment['msg']]);
        }
        if($repayment['result']['period_no'] != $params['period_no']){
            return $this->parse_data(['code' => 5000, 'msg' => '请您先交费上一期账单']);
        }
        //订单信息
        $order = $this->getWS('credit', 'apply@applyInfo', ['b_id' => $params['b_id']]);
        if($order['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '交费失败']);
        }

        $order = $order['result'];
        if (strtolower($order['fund_name']) == 'moma') {
            return $this->parse_data(['code' => 5000, 'msg' => '请保证银行卡余额充足，等待划扣']);
        }
        
        $res = $this->getWS('credit', 'repayment@repaymentAmt', ['b_id' => $params['b_id'], 'period_no' => $params['period_no']]);
        if ($res['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '订单信息有误']);
        }
        $repaymentAmt = $res['result']['repaymentAmt'];
        $r_id = $res['result']['r_id'];
        if (strtolower($order['fund_name']) == 'jinshang') {
            $data = [
                'service' => 'CF201017',
                'applseq' => $order['fund_loan_no'], //流水编号
            ];
            $return = $this->getWS('channel', 'jinshangfund@jinshangInterface', $data);
            if ($return['result']['ec'] != '0') {
                return $this->parse_data(['code' => 5000, 'msg' => '获取合同号失败']);
            }
            
            $res = $this->getWS('credit', 'trace@transaction', ['amount' => $repaymentAmt, 'pay_channel' => '6', 'status' => '0', 'r_ids' => $r_id, 'b_id' => $params['b_id'], 't_bank_name' => $order['ub_bank_name'], 't_bank_card_code' => $order['ub_card_no']]);
            if ($res['status'] != '2000') {
                return $this->parse_data(['code' => 5000, 'msg' => '添加交易记录失败']);
            }
            $chlfkseq = $res['result']['t_id'];

            $data = [
                'service' => 'CF201013',
                'applseq' => $order['fund_loan_no'], //流水编号
                'chlfkseq' => $chlfkseq, //渠道交费流水号
                'contno' => $return['result']['contno'], //合同编号
                'dnamt' => '', //交费金额 如果交费类型是NF时，不传该值
                'paymentmode' => ($order['b_status'] == '3001' || $order['repay_day'] == date('d'))?'NM':'NF', //交费类型 提前结清：FS 部分交费：ER 到期交费：NM 按期交费：NF
                'perdno' => $params['period_no'], //期数 如果交费类型传NF，该字段为必传项，表示当前要还的期数，例如：1,2,3,4,5,6
                'flag' => '0', //NF标识 如果交费类型传NF，该字段为必传项，字典项：0：NF交费只能还一期；1：NF交费还多期
            ];
            $return = $this->getWS('channel', 'jinshangfund@jinshangInterface', $data);
            if ($return['result']['ec'] == '0' || $return['result']['ec'] == 'E0001') {
                $pq_extends = ['r_ids' => [$r_id], 'transaction_no' => $chlfkseq, 'pay_channel' => '6', 'fund_loan_no' => $order['fund_loan_no']];
                if(!empty($return['result']['lmseq'])){
                    $pq_extends['fund_lmseq'] = $return['result']['lmseq'];
                }
                
                $data = [
                    "b_id" => $order['b_id'],
                    "pq_amt" => $repaymentAmt,
                    "pq_time" => 0,
                    "pq_add_time" => date("Y-m-d H:i:s"),
                    "pq_type" => 4,
                    "pq_extends" => json_encode($pq_extends)
                ];
                $result = $this->getWS('credit', 'repayment@saveQueue', ['data' => $data]);
                if ($result['status'] != '2000') {
                    return $this->parse_data(['code' => 5000, 'msg' => '交费异常，请稍后重试']);
                }
                
                return $this->parse_data(['code' => 5000, 'msg' => '交费请求提交成功，请等待处理']);
            }else{
                //修改为失败
                $result = $this->getWS('credit', 'repayment@updateRepayment', ['r_id' => $r_id, 't_id' => $chlfkseq, 'status' => '2', 'pay_channel' => '6']);
                if ($result['status'] != '2000') {
                    return $this->parse_data(['code' => 5000, 'msg' => '交费失败']);
                }

                return $this->parse_data(['code' => 5000, 'msg' => '交费失败']);
            }
            
        } else {
            // 连连支付
            $payData = [
                'phone' => $order['ub_phone'],
                'u_code' => $order['u_code'],
                'id_no' => $order['u_ident_no'],
                'acct_name' => $order['u_true_name'],
                'no_order' => 'NO'.date('YmdHis').$r_id,
                'money_order' => sprintf("%1\$.2f", $repaymentAmt),
                'card_no' => $order['ub_card_no'],
                'info_order' => $params['b_id'].'|'.$params['period_no'],
            ];
            $llpay = $this->getWS('channel', 'pay@pay', $payData);

            return $this->parse_data(['data' => ['isJump' => true, 'content' => $llpay['result']]]);
        }
    }

}
